
// import QN from './QN.js'
import QN from './qn_sdk.js'
// import gxc_demo from './gxc_demo.js'

console.log('QN', QN)

/* let a = QN.formatItemData([{ "type": 1, "value": 66.8 }, { "type": 2, "value": 22.3 }, { "type": 3, "value": 19.9 }, { "type": 4, "value": 18.0 }, { "type": 5, "value": 5 }, { "type": 6, "value": 57.8 }, { "type": 7, "value": 51.8 }, { "type": 8, "value": 2.68 }, { "type": 9, "value": 1525.0 }, { "type": 10, "value": 4 }, { "type": 11, "value": 18.25 }, { "type": 12, "value": 53.52 }, { "type": 13, "value": 50.83 }, { "type": 14, "value": 24 }, { "type": 15, "value": 95.9 }]) */
let a = {
  "visfat": 9,
  "bodyAge": 41,
  "muscleMass": 53.46,
  "user_id": 5,
  "subfat": 24.7,
  "weight": 78.05,
  "bmi": 27,
  "update_time": "2020-05-07 13:40:32",
  "bodyfat": 27.9,
  "water": 52.1,
  "bmr": 1585,
  "bodyShape": 6,
  "score": 73.5,
  "create_time": "2020-05-07 13:40:32",
  "protein": 16.4,
  "muscle": 46.6,
  "lbm": 56.31,
  "bone": 2.82,
  "report_id": 50
}
a.birthday = '1980-05-22'
a.gender = 1
a.height = 170
// a.time = 1273141154000
console.log('a', a)
let resultData = QN.reportData(a)

console.log('resultData', resultData)
resultData.reportItemList.forEach((item, i) => {
  console.log(i, item.name, item.value, item.level, item.levelNames[item.level], item.boundaries)
})

let currentDevice = null//用于存储当前设备

let ble = {
  discovery() {
    //开始扫描周围的设备
    wx.startBluetoothDevicesDiscovery({
      success: res => {
        console.log('开启扫描成功')
      },
      fail: err => {
        console.log('开启扫描失败')
      }
    })
  },
  stopDiscovery() {
    //扫到设备后，停止扫描
    wx.stopBluetoothDevicesDiscovery({
      success: res => {
        console.log('停止扫描成功')
      },
      fail: err => {
        console.log('停止扫描失败')
      }
    })
  }
}


Page({

  /**
   * 页面的初始数据
   */
  data: {
    weight: 0,
    available: false,
    discovering: false,
    connected: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  close() {
    let { connected } = this.data

    if (connected) {
      wx.closeBLEConnection({
        deviceId: currentDevice.deviceId,
        success: res => {
          currentDevice = null
          console.log('断开连接成功')
        },
        fail: err => {
          console.log('断开连接失败')
        }
      })
    }
  },
  discovery() {
    ble.discovery()
  },
  restart() {
    let { connected } = this.data
    if (connected) {
      wx.closeBLEConnection({
        deviceId: currentDevice.deviceId,
        success: res => {
          currentDevice = null
          console.log('断开连接成功')
          ble.discovery()
        },
        fail: err => {
          console.log('断开连接失败')
        }
      })
    } else {
      currentDevice = null
      ble.discovery()
    }
  },
  onLoad: function (options) {
    let fetchParams = QN.fetchParams({
      appid: 'mpplugin',//更换为正确的参数
      secret: '1c98652952a92301',//更换为正确的参数
      height: 173,//用户身高
      age: 29, //用户年龄
      gender: 1,//用户性别(1男0女)
      // encryptStr: 'b49886d28e8926af9a9b6e87'//对应的加密字符
      encryptStr: 'A69882D39689E4B8409B607D'//对应的加密字符
    })

    wx.request({
      method: 'post',
      url: 'http://api.yolanda.hk/open_api/calcs/qn.json',
      data: fetchParams,
      success: res => {
        console.log('请求结果', res)
        //得到resultData进行字段转换
        let data = QN.fieldTransform(res.data.resultData)
        console.log('data', data)
        //添加用户的生日
        data.birthday = '1990-01-01'
        // data.gender = 1
        // data.height = 170
        //通过reportData得到指标数组reportItemList
        let result = QN.reportData(data)
        console.log('result', result)
      }
    })
    //打开蓝牙模块
    wx.openBluetoothAdapter({
      success: res => {
        console.log('打开蓝牙模块成功')
        //开始扫描设备
        ble.discovery()
      },
      fail: err => {
        console.log('打开蓝牙模块失败')
      }
    })

    //监听蓝牙开关、是否有开启扫描设备
    wx.onBluetoothAdapterStateChange(res => {
      let { available, discovering } = res

      this.setData({
        available
      })

      if (available) {
        console.log('蓝牙已打开')
      } else {
        //清掉
        currentDevice = null
        console.log('蓝牙已关闭')
      }
    })

    //监听设备连接状态
    wx.onBLEConnectionStateChange(res => {
      let { deviceId, connected } = res

      this.setData({
        connected
      })
      if (connected) {
        console.log('连接成功')
      } else {
        console.log('连接已经断开')
      }

    })

    // ArrayBuffer转16进制字符串示例
    function ab2hex(buffer) {
      let hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('')
    }

    //监听低功耗蓝牙设备的特征值变化事件
    wx.onBLECharacteristicValueChange(({ deviceId, value }) => {
      //转成16进制字符
      value = ab2hex(value)

      //根据特征值变化，获取对应的返回结果
      let result = QN.cmd({
        device: currentDevice, 
        value
      })
      
      if (result) {
        let { code, weight, encryptStr } = result

        if (code == 3001) {//测量中
          this.setData({
            weight
          })
        } else if (code == 3002) {
          //心率秤首次返回的命令
          //通过encryptStr，算出对应的指标
          //再通过 QN.itemCmdString 获取对应的体脂、bmi命令，然后发布给体脂秤显示
          let fetchParams = QN.fetchParams({
            appid: 'appid',//更换为正确的参数
            secret: 'secret',//更换为正确的参数
            height: 170,//用户身高
            age: 26, //用户年龄
            gender: 1,//用户性别(1男0女)
            encryptStr: encryptStr//对应的加密字符
          })
          wx.request({
            method: 'post',
            url: 'http://api.yolanda.hk/open_api/calcs/qn.json',
            data: fetchParams,
            success: res => {
              console.log('请求结果', res)
              //根据获取的结果，传入对应的参数，获取到 cmdString
              result.cmdString = QN.itemCmdString({
                gender: 1,//用户性别（1男0女）
                bodyfat: res.data.resultData.bodyfat,//体脂率，类型值为3，此处只是例子数据，请根据 res 结果填写
                bmi: res.data.resultData.bmi//bmi，类型值2，此处只是例子数据，请根据 res 结果填写
              })

              const ab = new ArrayBuffer(result.cmdString.length)
              const dv = new DataView(ab)

              result.cmdString.forEach((value, index) => {
                dv.setUint8(index, value)
              })

              wx.writeBLECharacteristicValue({
                deviceId,
                serviceId: result.serviceId,
                characteristicId: result.writeCharacteristicId,
                value: ab,
                success: () => {
                  console.log('发送成功')
                }
              })
            }
          })
          
        }

        if (result.cmdString) {//向蓝牙秤发送命令

          if (code == 3003) {
            //拿到对应的encryptStr加密字符
            console.log('测量完成', encryptStr)
            //获取对应的参数再进行请求
            let fetchParams = QN.fetchParams({
              appid: 'appid',//更换为正确的参数
              secret: 'secret',//更换为正确的参数
              height: 170,//用户身高
              age: 26, //用户年龄
              gender: 1,//用户性别(1男0女)
              encryptStr: encryptStr//对应的加密字符
            })

            wx.request({
              method: 'post',
              url: 'http://api.yolanda.hk/open_api/calcs/qn.json',
              data: fetchParams,
              success: res => {
                console.log('请求结果', res)
                //得到resultData进行字段转换
                let data = QN.fieldTransform(res.data.resultData)
                //添加用户的生日
                data.birthday = '1990-01-01'
                //通过reportData得到指标数组
                let result = QN.reportData(data)
                console.log('result', result)
              }
            })
          }
          const ab = new ArrayBuffer(result.cmdString.length)
          const dv = new DataView(ab)

          result.cmdString.forEach((value, index) => {
            dv.setUint8(index, value)
          })

          wx.writeBLECharacteristicValue({
            deviceId,
            serviceId: result.serviceId,
            characteristicId: result.writeCharacteristicId,
            value: ab,
            success: () => {
              console.log('发送成功')
            }
          })
        }
      }

    })

    //监听寻找到新设备的事件
    wx.onBluetoothDeviceFound(devices => {
      let { localName, RSSI, advertisData, deviceId } = devices.devices[0]

      let deviceObj = {
        deviceId,
        localName,
        RSSI,
        advertisData: ab2hex(advertisData)//转成16进制字符
      }
      let device = QN.getDevice(deviceObj)//获取蓝牙设备

      if (device) {
        
        //如果是广播秤
        if (device.isBroadcast) {
          if (currentDevice && device.mac != currentDevice.mac) return
          
          currentDevice = device
          onBroadcastScale(device)//广播秤处理逻辑
        } else {//蓝牙秤
          currentDevice = device
          //扫到设备后停止扫描
          ble.stopDiscovery()

          createConnect()//蓝牙秤处理逻辑
        }
      }

    })

    let that = this
    //广播秤的处理
    function onBroadcastScale(device) {
      let { code, encryptStr, weight } = device
      
      if (code == 3001) {//测量中
        that.setData({
          weight
        })
      } else if (code == 3003) {//测量完成,得到encryptStr加密字符,并停止扫描
        console.log('测量完成', encryptStr)
        //测量完成，停止扫描，使广播秤不再接收数据
        ble.stopDiscovery()
      }
    }

    //与currentDevice蓝牙设备的连接
    function createConnect() {
      let { deviceId } = currentDevice

      //连接扫描到的设备
      wx.createBLEConnection({
        deviceId,
        success: res => {

          //获取设备特征值
          wx.getBLEDeviceServices({
            deviceId,
            success: res => {
              console.log('getBLEDeviceServices res', res)
              //存储当前设备的服务
              let currentServices = QN.getServices(res.services)
              console.log('currentServices', currentServices)
              //获取蓝牙设备某个服务中所有特征值
              wx.getBLEDeviceCharacteristics({
                deviceId,
                serviceId: currentServices.serviceId,
                success: res => {

                  //启用低功耗蓝牙设备特征值变化时的 notify 功能
                  wx.notifyBLECharacteristicValueChange({
                    state: true, // 启用 notify 功能
                    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                    deviceId,
                    // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                    serviceId: currentServices.serviceId,
                    // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                    characteristicId: currentServices.readCharacteristicId,
                    success: res => {
                      console.log('创建连接成功完成')
                      
                    },
                    fail: err => {
                      console.log('创建连接成功失败')
                    }
                  })
                },
                fail: err => {
                  console.log('获取特征值失败 err', err)
                }
              })

            },
            fail: err => {
              console.log('获取服务失败 err', err)
            }
          })

        },
        fail: err => {
          console.log('蓝牙连接失败')
        }
      })
  
      
    }
  }
})